/*
 * @Author: 小花
 * @Date: 2022-04-07 08:59:22
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-28 20:00:39
 * @FilePath: /permission_client/src/request/axios.ts
 * @Description:
 */
import router from '@/router'
import { useStore } from '@/store'
import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import nProgress from 'nprogress'

import { responseEnum, responseUtil } from './responseUtil'

axios.defaults.baseURL = 'http://localhost:8088'
axios.defaults.timeout = 15000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

axios.interceptors.request.use((config: AxiosRequestConfig) => {
  const headers = config.headers as AxiosRequestHeaders
  nProgress.start()
  const store = useStore()
  headers.satoken = store.loginInfo.satoken || ''
  return config
}, (error) => {
  return Promise.reject(error)
})

axios.interceptors.response.use((response: AxiosResponse<responseUtil>) => {
  nProgress.done()
  if (response.data.code === responseEnum.LOGIN_FAILURE) {
    useStore().$reset()
    ElMessage.warning(response.data.msg)
    router.push({
      path: '/login',
      query: {
        redirect: router.currentRoute.value.path
      }
    })
    return Promise.reject(new Error(response.data.msg))
  }
  return response
}, (error) => {
  return Promise.reject(error)
})

export default axios
